package com.aboverock.common.helper;

import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.TableInfoHelper;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据库基础信息处理， 通过MybatisPlus的TableInfo根据实体类名获取表名和列名.
 *
 * @author Rock Wang
 */
public class MetadataHelper {

    private static final Logger logger = LoggerFactory.getLogger(MetadataHelper.class);
    /**
     * 根据java bean的本地变量名获取数据库表栏位名.
     *
     * @param <T> the generic type
     * @param clazz the clazz
     * @param variables the variables
     * @return the string[]
     */
    public static <T> String[] convertVariable2Column(Class<T> clazz, String... variables) {        
        TableInfo tableInfo = TableInfoHelper.getTableInfo(clazz);
        return Arrays.stream(variables).map(variable -> {
            List<TableFieldInfo> fieldList = tableInfo.getFieldList();
            Optional<TableFieldInfo> filed = fieldList.stream()
                    .filter(fiedlInfo -> fiedlInfo.getProperty().equals(variable)).findFirst();

            if (filed.isPresent()) {
                return filed.get().getColumn();
            }
            logger.warn("there is no variable: {} in class {}", variable, clazz.getName());
            return null;
        }).toArray(String[]::new);
    }
    
    /**
     * 根据java bean的本地变量名获取数据库表栏位名.
     *
     * @param <T> the generic type
     * @param clazz the clazz
     * @param variable the variable
     * @return the string
     */
    public static <T> String convertVariable2Column(Class<T> clazz, String variable ) {        
        TableInfo tableInfo = TableInfoHelper.getTableInfo(clazz);
        Optional<TableFieldInfo> filed = tableInfo.getFieldList().stream()
                .filter(fiedlInfo -> fiedlInfo.getProperty().equals(variable)).findFirst();
        if (filed.isPresent()) {
            return filed.get().getColumn();
        }
        logger.warn("there is no variable: {} in class {}", variable, clazz.getName());
        return null;
    }
    
    /**
     * 获取实体类对应的数据库表名.
     *
     * @param clazz the clazz
     * @return the table name
     */
    public static String getTableName(Class<?> clazz) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(clazz);
        if (tableInfo != null) {
            return tableInfo.getTableName();
        }
        return null;
    }

}
